﻿using System.Text.Json.Serialization;
using System.Text.Json;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class DateTimeConverterProvider : JsonConverter<DateTime>
    {
        private readonly string _dateFormatString;
        /// <summary>
        /// 
        /// </summary>
        public DateTimeConverterProvider()
        {
            _dateFormatString = "yyyy-MM-dd HH:mm:ss";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dateFormatString"></param>
        public DateTimeConverterProvider(string dateFormatString)
        {
            _dateFormatString = dateFormatString;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="typeToConvert"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return DateTime.Parse(reader.GetString()!);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(_dateFormatString));
        }
    }
}
